import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.xml.parsers.*;
import javax.xml.soap.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;

import org.w3c.dom.*;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

public class WeatherReport {

	
    /**
     * Starting point for the SAAJ - SOAP Client Testing
     */
    public static void main(String args[]) {
        try {
            // Create SOAP Connection
            SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
            SOAPConnection soapConnection = soapConnectionFactory.createConnection();

            // Send SOAP Message to SOAP Server
            String url = "http://wsf.cdyne.com/WeatherWS/Weather.asmx";
            SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(), url);

            // Process the SOAP Response
            printSOAPResponse(soapResponse);
            printXMLTree();
            //printXMLFile();
           
            soapConnection.close();
            //eraseXML();
            
        } catch (Exception e) {
            System.err.println("Error occurred while sending SOAP Request to Server");
            e.printStackTrace();
        }
    }

    private static SOAPMessage createSOAPRequest() throws Exception 
    {
        MessageFactory messageFactory = MessageFactory.newInstance();
        SOAPMessage soapMessage = messageFactory.createMessage();
        SOAPPart soapPart = soapMessage.getSOAPPart();

        String serverURI =  "http://ws.cdyne.com/WeatherWS/";

        // SOAP Envelope
        SOAPEnvelope envelope = soapPart.getEnvelope();
        envelope.addNamespaceDeclaration("weather", serverURI);

        // SOAP Body
        SOAPBody soapBody = envelope.getBody();
        SOAPElement soapBodyElem = soapBody.addChildElement("GetCityWeatherByZIP", "weather");
        SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("ZIP", "weather");
        soapBodyElem1.addTextNode("12345");

        MimeHeaders headers = soapMessage.getMimeHeaders();
        //THIS IS IMPORTANT. WATCH IT OUT!!!!!
        headers.addHeader("SOAPAction", "http://ws.cdyne.com/WeatherWS/GetCityWeatherByZIP");

        soapMessage.saveChanges();

        /* Print the request message */
        System.out.print("Request SOAP Message = ");
        soapMessage.writeTo(System.out);
        System.out.println();

        return soapMessage;
    }

    /**
     * Method used to print the SOAP Response
     */
    private static void printSOAPResponse(SOAPMessage soapResponse) throws Exception 
    {
        
    	TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        Source sourceContent = soapResponse.getSOAPPart().getContent();
        System.out.print("\nResponse SOAP Message = ");
        StreamResult result = new StreamResult(System.out);
        transformer.transform(sourceContent, result);
        FileOutputStream out = new FileOutputStream(System.getProperty("user.dir")+"\\soapresponse.xml");
        soapResponse.writeTo(out);
        out.close();
    }
    
    
    private static void printXMLFile() 
    		throws ParserConfigurationException, SAXException, IOException
    {  	
    	String xml="soapresponse.xml";
    	File fXmlFile = new File(xml);
    	DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    	DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    	Document doc = dBuilder.parse(fXmlFile);
     
    	doc.getDocumentElement().normalize();
     
    	//System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
        System.out.println();

    	System.out.println("========================");

    	//NodeList nodeList = doc.getElementsByTagName("GetCityWeatherByZIPResult");
    	NodeList nodeList = doc.getElementsByTagName("*");

    	
        for (int i = 0; i < nodeList.getLength(); i++)
        {
            Node node = nodeList.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) 
            {
               System.out.println(node.getNodeName()+": "+node.getTextContent());               
            }
        }
    		  
    		
    }
       
       
    private static boolean isGoodEmail() //OBSELETE
    		throws ParserConfigurationException, SAXException, IOException
    {
    	String xml="soapresponse.xml";
    	String ans=null;
    	boolean result = false;
    	File fXmlFile = new File(xml);
    	DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    	DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    	Document doc = dBuilder.parse(fXmlFile);
     
    	doc.getDocumentElement().normalize();
     
    	NodeList nList = doc.getElementsByTagName("VerifyEmailResult");
          
    	for (int temp = 0; temp < nList.getLength(); temp++) 
    	{
     
    		Node nNode = nList.item(temp);
         
    		if (nNode.getNodeType() == Node.ELEMENT_NODE) 
    		{
     
    			Element eElement = (Element) nNode;
     
    			ans = eElement.getElementsByTagName("GoodEmail").item(0).getTextContent();
    			
    		}
    	 }
    	result = Boolean.getBoolean(ans);
    	return result;
       
    }
    
    
    
    private static void printXMLTree() 
    		throws ParserConfigurationException, SAXException, IOException
    {  	
    	String xml="soapresponse.xml";
    	File fXmlFile = new File(xml);
    	DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    	DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    	Document doc = dBuilder.parse(fXmlFile);
     
    	doc.getDocumentElement().normalize();
     
    	//System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
        System.out.println();

    	System.out.println("========================");

    	NodeList nodes = doc.getElementsByTagName("GetCityWeatherByZIPResult");
    	//NodeList nodes = doc.getElementsByTagName("*");

    	
    	for (int i = 0; i < nodes.getLength(); i++) 
    	{
    		Node node = nodes.item(i);
    		//System.out.print(i+"---");
    		if(node.hasChildNodes()==true)
    		{
    			System.out.println(node.getNodeName());
    			
    			Node child = node.getFirstChild();
        		while(node.getNextSibling()!=null)
        		{
                    if (child.getNodeType() == Node.ELEMENT_NODE) 
                    {
                       System.out.println(child.getNodeName()+": "+child.getTextContent());               
                    }

        		}
    		}
    		
    		
    		
    	  if (node instanceof Element) {
    	    Element childElement = (Element) node;
    	    System.out.println("tag name: " + childElement.getTagName());
    	  }
    	}
    		  
    		
    }
       

    
    private static void eraseXML()
    {
    	String xml="soapresponse.xml";
    	File file = new File(xml);
    	if(file.delete()){
			System.out.println(file.getName() + " is deleted!");
		}else{
			System.out.println("Delete operation is failed.");
		}
    }
    
    
    
    
    

}